package com.kuang.demo02;

/**测试生产者消费者问题
 * 方式二：
 *  标志位解决(信号灯法)
 *      这个信号灯就是本例中的flags
 * @author FHL
 */
public class TestPC2 {
    public static void main(String[] args) {
TV tv=new TV();
new Player(tv).start();
new Watcher(tv).start();
    }
}
//生产者，演员
class Player extends Thread{
    TV tV=new TV();
    public Player(TV tv){
        this.tV = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0){
                this.tV.play("演员正在表演节目，，，，");
            }else {
               this.tV.play("广告时间###########################");
            }
        }
    }
}
//消费者，观众
class Watcher extends Thread{
TV tv=new TV();
public Watcher(TV tv){
    this.tv=tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            this.tv.watch();
        }

    }
}
//产品，节目
class TV{
    //演员表演，观众等待 true
    //观众观看，演员等待 false
    String voice;
    //节目
    boolean flags=true;
    //表演
    public synchronized void play(String voice){
       if (!flags){
           try {
               this.wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
        System.out.println("演员表演了"+voice);
        //唤醒观众来看节目
        this.notifyAll();
        this.voice=voice;
        this.flags=!this.flags;
    }
    //观看

public synchronized void watch(){
    if (flags){
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println("观众观看了"+voice);
    //通知演员表演
    this.notifyAll();
    this.flags=!this.flags;
}
}
